/**
 * Created by yuanyue on 2014-08-15.
 */
package com.eastcom.groovy.task.taskdirector.db.procedure
import oracle.jdbc.driver.OracleTypes;

import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.apache.log4j.TTCCLayout;
import org.springframework.beans.factory.BeanFactory
import org.springframework.beans.factory.support.BeanDefinitionRegistry
import org.springframework.beans.factory.support.DefaultListableBeanFactory
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader
import org.springframework.core.io.FileSystemResource
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import com.eastcom.groovy.config.GroovyScript
import com.eastcom.groovy.config.TaskConfig
import com.eastcom.groovy.context.ServerContext
import com.eastcom.groovy.context.TaskContext
import com.eastcom.groovy.provider.DbContextProvider
import com.eastcom.groovy.provider.DynamicBeanRegisterProvider
import com.eastcom.groovy.provider.SpringContextProvider
import com.eastcom.groovy.task.Task
import com.eastcom.groovy.tools.db.DbEngine
import com.eastcom.groovy.tools.common.DateUtils;
import com.eastcom.groovy.tools.common.MQCommunication;
import com.eastcom.groovy.tools.db.DbInfo
import com.eastcom.groovy.tools.db.Table
import com.eastcom.groovy.tools.file.GroovyUtil
import com.eastcom.groovy.tools.file.JaxbUtil
import com.eastcom.groovy.tools.TaskUtil
import com.eastcom.groovy.tools.db.DbEngine

import javax.xml.bind.annotation.XmlAccessType
import javax.xml.bind.annotation.XmlAccessorType
import javax.xml.bind.annotation.XmlElement
import javax.xml.bind.annotation.XmlRootElement
import javax.xml.bind.annotation.XmlTransient

import java.sql.CallableStatement
import java.sql.Timestamp
import java.sql.Types
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher
import java.util.regex.Pattern

import com.eastcom.groovy.provider.*
import com.sun.org.apache.bcel.internal.generic.NEW;
DbEngine dbEngine;
/**
 * Created by yuanyue on 2014-08-13.
 */
/**
 * 执行方法
 * @param jobId
 */
class SimpleDatabaseProcedureTaskDirectorA{
	/**
	 * 一个源资源对应一个目的资源，一个源资源会有多个SQL
	 */
	final String[] dstDbbean =
	[
		"sybase_zj_142",
		"oracle_zj_ipnet_132"
	]
	final String[] srcBean =
	[
		"oracle_mms_41"
	]
	String[] insertSql =
	[
		"insert into MMS_KPI_DAILY(ALL) values(?)",
		"insert into MMS_KPI_DAILY(ALL) values(?)"
	]
	final String timeFormat = "yyyy-MM-dd"

	final String[][] sqls =
	[
		[
			"call MMS_KPIDay(?,'?','?',9)",
			"call MMS_Day(?,'?','?',9)",
			"call MMS_Hour(?,'?','?','?',9)"
		]

	]

	final String[][][] sqlOutOrIn =
	[
		[
			["out","in","in"],
			["out","in","in"],
			["out","in","in","in"]
		]
	]
	final String[][] cursorKeys =
	[
		[
			["SDAY","IMMSBUSY","IMMSBUSY","IUSERCOUNT","IUSEUSER","IPTCOUNT","ISPTCOUNT","IPTRATE","IOCOUNT","ITCOUNT","INFOCOUNT","IUFOCOUNT","INFTCOUNT","IUFTCOUNT","ICXNAPCT","ICXUAPCT","ICXAPCT"],
			[],
			[]
		]
	]


	static ThreadPoolTaskExecutor threadPoolTaskExecutor
	static List<List<String>> dstFieldList = new ArrayList()
	static List<List<String>> sqlTypes
	static List<List<Integer>> dstFieldTypeList = new ArrayList()
	static List<List<List<Object>>> parseResultList = new ArrayList()
	static Log logger = LogFactory.getLog(SimpleDatabaseProcedureTaskDirectorA.class)
//	String dstdbBean,List<String> dstFieldList,List<String> dstFieldTypeList,int[] sqlTypes,String insertSql,boolean isDomain
	public boolean initJob(String jobId){
		doDbInit()
	}

	public boolean doJob(String jobId) {
		DbEngine dbEngine = SpringContextProvider.getBean("dbEngine")

		for(int i = 0; i < srcBean.length; i++){
			dbEngine.getJdbcUtil().setDataSource(DynamicBeanDomianProvider.getBean(srcBean[i]))
			sqls.each {
				it.each {
					String sql = it
					Calendar calendar = Calendar.getInstance()
					calendar.setTime(new Date())
					int y = calendar.get(Calendar.YEAR)
					int m = calendar.get(Calendar.MONTH)
					String year = String.valueOf(y)
					String month = String.valueOf(m)

					Object[] param = new Object[3]

					param[0] = null
					param[1] = year
					param[2] = month

					String[] outOrIn = ["out","in","in"]

					int[] types = [OracleTypes.CURSOR,Types.VARCHAR, Types.VARCHAR]

					List<String> cursorKeys = new ArrayList()
					cursorKeys.add("SDAY")
					cursorKeys.add("IMMSCOUNT")
					cursorKeys.add("IMMSBUSY")
					cursorKeys.add("IUSERCOUNT")
					cursorKeys.add("IUSEUSER")
					cursorKeys.add("IPTCOUNT")
					cursorKeys.add("ISPTCOUNT")
					cursorKeys.add("IPTRATE")
					cursorKeys.add("IOCOUNT")
					cursorKeys.add("ITCOUNT")
					cursorKeys.add("INFOCOUNT")
					cursorKeys.add("IUFOCOUNT")
					cursorKeys.add("INFTCOUNT")
					cursorKeys.add("IUFTCOUNT")
					cursorKeys.add("ICXNAPCT")
					cursorKeys.add("ICXUAPCT")
					cursorKeys.add("ICXAPCT")
					try {
						List<Object> result = dbEngine.executeStoredProcedure(sql, param, outOrIn, types, cursorKeys)
						println result.size()
						//		List<Object> temp = result.get(0)
						List cursorResult = result.get(0)
						cursorResult.each {
							Map rs = it
							List<String> ob = new ArrayList()
							int index
							rs.values().each {
								index++
								//					if(index == ){
								//
								//					}
								//					ob.add(it)
							}
						}
					} catch (Exception e) {
						e.printStackTrace()
					}
				}
			}
		}


		println "目的资源处理完成!"
		println "任务" + jobId + "完成！"
		println "wodkjfsdskfsdkfsdk"
		return true
	}

	private doDbInit(){
		try{
			String reg = "\\w+\\s+\\w+([^\\(\\),]+)\\s*\\(([^\\)]+)"
			String dstTb
			String dstFields
			Pattern pattern = Pattern.compile(reg)

			for(int i = 0; i < dstDbbean.length; i++){
				String temSql = insertSql[i]
				List<String> dstFeildLst = new ArrayList<String>()
				List<Integer> dstFeildTypeLst = new ArrayList<Integer>()
				List<String> sqlTypeLst = new ArrayList<String>()
				dstFieldList.add(dstFeildLst)
				dstFieldTypeList.add(dstFeildTypeLst)
				sqlTypes.add(sqlTypeLst)
				Matcher matcher = pattern.matcher(temSql)
				if(matcher.find()){
					dstTb = matcher.group(1)
					dstFields = matcher.group(2)
				}
				DbEngine.loadDb(dstDbbean[i], dstTb, dstFields, dstFeildLst, dstFeildTypeLst, true)
				if(dstFields.equalsIgnoreCase("ALL")){
					insertSql[i] = DbEngine.makeSql(dstFeildLst, dstTb)
				}
				for(int a = 0; a < dstFeildTypeLst.size(); a++){
					sqlTypeLst.add(dstFeildTypeLst.get(a))
				}
			}

		}catch (Exception e) {
			e.printStackTrace()
			logger.error(e.getMessage())
		}
	}

	private void doCollect(){
		DbEngine dbEngine = SpringContextProvider.getBean("dbEngine")
		for(int i = 0; i < srcBean.length; i++){
			dbEngine.getJdbcUtil().setDataSource(DynamicBeanDomianProvider.getBean(srcBean[i]))
			String[] sql = sqls[i]
			for(int j = 0; j < sql.length; j++){


			}
		}

	}


	private boolean doInsertResult(){
		try{
			DbEngine dbEngine = SpringContextProvider.getBean("dbEngine")
			dbEngine.getJdbcUtil().setDataSource(DynamicBeanDomianProvider.getBean(dstDbbean[1]))
			println parseResultList.size()
			for(List<String> raw: parseResultList){
				Object[] param = new Object[raw.size()+1]
				for(int i = 0; i < raw.size(); i++){
					print raw.get(i)+"--"+sqlTypes[i]+"\t"
					try {
						switch(sqlTypes[i]){
							case Types.INTEGER:
								param[i] = Integer.valueOf(raw.get(i))
								break
							case Types.FLOAT:
							case Types.DOUBLE:
								param[i] = Double.valueOf(raw.get(i))
								break
							case Types.DECIMAL:
							case Types.NUMERIC:
								param[i] = BigDecimal.valueOf(Double.valueOf(raw.get(i)))
								break
							case Types.TIMESTAMP:
								java.util.Date date = new SimpleDateFormat(timeFormat).parse(raw.get(i))
								logger.debug(date)
								param[i] = new Timestamp(date.getTime())
								break
							case Types.DATE:
								java.util.Date date = new SimpleDateFormat(timeFormat).parse(raw.get(i))
								logger.debug(date)
								param[i] = new java.sql.Date(date.getTime())
								break
							case Types.VARCHAR:
							case Types.NVARCHAR:
								param[i] = raw.get(i)
								break
							case Types.OTHER:
								param[i] = raw.get(i)
								break;
							default:
								param[i] = null
								logger.warn("入库数据库字段无法识别！使用Null插入！")
								break;
						}
					} catch (Exception e) {
						e.printStackTrace()
						logger.error(e.getMessage())
						param[i]=null
					}
				}
				try {
					dbEngine.getJdbcUtil().update(insertSql, param, sqlTypes)
				} catch (Exception e) {
					e.printStackTrace()
				}
				println ""
			}
			println "sdfdsfdsdone!"
			parseResultList.clear()
		}catch (Exception e) {
			e.printStackTrace()
			logger.error(e.getMessage())
		}
	}
}